/**
 * 字节对象转字符串
 * @param {Object} arr
 */

export const byteToString = function (arr) {
  if (typeof arr === "string") {
    return arr;
  }

  var str = "";
  var i = 0;

  while (i < arr.length) {
    var byte = arr[i];
    var one = byte.toString(2);
    var bytesLength = 0;

    // 检测是否为多字节字符
    while (one[bytesLength] === "1") {
      bytesLength++;
    }

    if (bytesLength === 0) {
      // 单字节字符
      str += String.fromCharCode(byte);
    } else if (bytesLength === 1 && one.length === 8) {
      // 部分多字节字符
      var store = one.slice(2);

      for (var st = 1; st < bytesLength; st++) {
        i++;
        store += arr[i].toString(2).slice(2);
      }

      str += String.fromCharCode(parseInt(store, 2));
    } else {
      // 非法字符
      str += String.fromCharCode(byte);
    }

    i++;
  }

  return str;
};

/**
 * 字符串转字节
 * @param {Object} str
 */

export const string2ArrayBuffer = function (str) {
  // 首先将字符串转为16进制
  let val = "";
  for (let i = 0; i < str.length; i++) {
    if (val === "") {
      val = str.charCodeAt(i).toString(16);
    } else {
      val += "," + str.charCodeAt(i).toString(16);
    }
  }
  // 将16进制转化为ArrayBuffer
  return new Uint8Array(
    val.match(/[\da-f]{2}/gi).map(function (h) {
      return parseInt(h, 16);
    })
  ).buffer;
};

/**
 * 格式化得到aid值
 * @param {Object} buffer
 */
export const ab2hex = function (buffer) {
  const data = new Uint8Array(buffer);
  let str = "";
  data.forEach((e) => {
    let item = e.toString(16);
    if (item.length == 1) {
      item = "0" + item;
    }
    item = item.toUpperCase();
    str += item;
  });
  return str;
};
